package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //组装成父子的树形结构
        //1.找到所有的一级分类   stream类似于iterator高级，返回父分类为0的，说明是一级分类，然后最后collect转为list集合
        /*这是查询一级分类的方法
     List<CategoryEntity> level = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).collect(Collectors.toList());*/

        List<CategoryEntity> level = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{
            //把子分类放入
            //根据当前菜单和所有菜单查询当前菜单的子菜单
            List<CategoryEntity> childrenList = getChildrens(menu, entities);
            menu.setChildren(childrenList);
            return menu;
        }).sorted((menu1,menu2)->{//排序 前面一个菜单1，后面一个菜单2，两个对比
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }
    /**
     * 根据catlogId获取分类完整路径，用于修改时候分类不存在
     * [父/子/孙]
     * @return
     * @throws
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths=new ArrayList<>();
        //[2,25,255]
        List<Long> parentPath = findParenth(catelogId, paths);
        //正序转为逆序   完整路径[2, 34, 225]
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }
    /**
     * 级联更新所有关联的数据，比如，分类关联表中的名称
     * @return
     * @throws
     */
    @Transactional
    @Override
    public void updateCasecade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    //225分类id   [225,25,2]
    private List<Long> findParenth(Long catelogId,List<Long> paths){
        //收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){//寻找父分类
            findParenth(byId.getParentCid(),paths);
        }
        return paths;
    }


    /**递归查找
     * * 获取某一个菜单的子菜单
     * @param root 当前菜单
     * @param all 所有菜单
     * @return
     * @throws
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        //查询子菜单，以及子菜单中的子菜单
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //子菜单当中还有可能有子菜单，所以继续调用过滤
            List<CategoryEntity> cldList = getChildrens(categoryEntity, all);
            categoryEntity.setChildren(cldList);
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    @Override
    public List<CategoryEntity> getLevelCategorys() {
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }


    public void setRedisCatalogDatas(){
        //给缓存中放入json字符串，拿出的json字符串逆转为能用的对象类型【序列化与反序列化】

        //1.加入缓存逻辑，缓存丶中存的数据是json字符串
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(StringUtils.isEmpty(catalogJson)){
            //2缓存中没有查询数据库
            Map<String,List<Catelog2Vo>> map=null;
            //3.查询到的数据放入缓存
            String jsonString = JSON.toJSONString(map);
            redisTemplate.opsForValue().set("catalogJson",jsonString);
        }
        //从redis取出来，转为指定的对象 ，匿名内部类的方式new  TypeReference            Map<String,List<Catelog2Vo>> result=
        Map<String,List<Catelog2Vo>> result=  JSON.parseObject(catalogJson,new TypeReference<Map<String,List<Catelog2Vo>>>(){});

    }



    @Override
    public  Map<String, List<Catelog2Vo>> getCatalogJson() {
        //1.查出所有一级分类
        List<CategoryEntity> leve1 = getLevelCategorys();
        //2.封装数据
        Map<String, List<Catelog2Vo>> parent_cid = leve1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.每一个一级分类查到这个分类的二级分类
            List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            //2、封装上面的结果
            List<Catelog2Vo> collect = null;
            if (entities != null) {
                collect = entities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //3.查找当前2级分类的三级分类封装成vo
                    List<CategoryEntity> leve3 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if(leve3!=null){
                        List<Catelog2Vo.catelog3Vo> cll3 = leve3.stream().map(l3 -> {
                            //分装成指定格式
                            Catelog2Vo.catelog3Vo catelog3Vo = new Catelog2Vo.catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatelog3List(cll3);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        return parent_cid;
    }
}